game_reset = document.getElementById("game_reset");
first_hand_botton = document.getElementById("first_hand");
web_body = document.getElementById("body");

// 横向为x，纵向为y
chess_width = 50;
chess_board = document.getElementById("chess_board");
let real_table_position = [chess_board.offsetLeft, chess_board.offsetTop];
let mouse_position = [0, 0];
let first_hand = "machine";
let chess_images = [];
let game_finished = false;

// 定义棋盘状态矩阵，为11×11，0表示无子，1表示白，2表示黑
// 玩家为白，机器为黑。
chess_state = [];
for (let i = 0; i < 11; i++) {
    let zero_row = [];
    for (let j = 0; j < 11; j++) {
        zero_row[j] = 0;
    }
    chess_state[i] = zero_row;
}

// 获取鼠标位置
document.addEventListener ("click", function (e) {
    mouse_position = [e.clientX, e.clientY];
})


function sleep (time) {
    return new Promise(resolve => {setTimeout(resolve, time)});
}


// 放置棋子函数，由位置和颜色决定。
function chess_creator (pos, color) {
    let new_chess = document.createElement("img");
    chess_images.push(new_chess);
    if (color === "black") {
        new_chess.src = "black_piece.png";
        chess_state[pos[0]][pos[1]] = 2;
    }
    else {
        new_chess.src = "white_piece.png";
        chess_state[pos[0]][pos[1]] = 1;
    }
    // 设置图片属性要使用style
    new_chess.style.position = "absolute";
    new_chess.style.height = "50px";
    new_chess.style.width = "50px";
    new_chess.style.left = (pos[0] + 1) * 100 - chess_width / 2 + real_table_position[0] - 100 + 'px';
    new_chess.style.top = (pos[1] + 1) * 100 - chess_width / 2 + real_table_position[1] - 100 + 'px';
    web_body.appendChild(new_chess);
    sleep(50).then( () => {
        win_lose_judge(color);
        if (is_full() === true) {
            game_finished = true;
            end_game(color, true);
        }
    });
}


// 下棋的主函数，人先下一步，机器再下一步
function human_put_new_chess () {
    let relative_pos_from_board = [mouse_position[0] - real_table_position[0], mouse_position[1] - real_table_position[1]];
    let new_chess_position = [Math.floor((relative_pos_from_board[0] + 50) / 100), Math.floor((relative_pos_from_board[1] + 50) / 100)];
    if (new_chess_position[0] <= 10 && new_chess_position[1] <= 10) {
        if (chess_state[new_chess_position[0]][new_chess_position[1]] === 0) {
            chess_creator(new_chess_position, "white");
            if (!game_finished) {
                let machine_chess_position = machine_put_new_chess();
                chess_creator(machine_chess_position, "black");
            }
        }
    }
    document.onclick = human_put_new_chess;
}


function machine_put_new_chess() {
    for (let i = 0; i < 11; i ++) {
        for (let j = 0; j < 11; j++) {
            if (chess_state[i][j] === 0) {
                return [i, j];
            }
        }
    }
}


function game_start () {
    if (first_hand === "machine") {
        alert("machine is the first");
        chess_creator([5, 5], "black");
    }
    else {
        alert("you are the first");
    }
    document.onclick = human_put_new_chess;
}


function start_change () {
    first_hand = "human";
}


function end_game (color, full) {
    if (full === true) {
        alert("no winner in this game");
    }
    else {
        if (color === "white") {
            alert("you win!");
        }
        else {
            alert("the machine wins!");
        }
    }
    for (let i = 0; i < 11; i++) {
        for (let j = 0; j < 11; j++) {
            chess_state[i][j] = 0;
        }
    }
    for (let i = 0; i < chess_images.length; i++) {
        web_body.removeChild(chess_images[i]);
    }
    chess_images = [];
    let choose_first_hand = confirm("Confirm is machine first. Cancel is you first");
    if (choose_first_hand === true) first_hand = "machine";
    else first_hand = "human";
    sleep(500).then(() => {
        game_finished = false;
        game_start();
    });
}


// 判断胜负
function win_lose_judge (color) {
    // 分类，如果是人下完那么判断人（白），如果是机器下完那么判断机器（黑）。
    let color_mark = 0;
    if (color === "white") {
        color_mark = 1;
    }
    else {
        color_mark = 2;
    }

    for (let i = 0; i < 11; i++) {
        for (let j = 0; j < 11; j++) {
            if (chess_state[i][j] === color_mark) {
                if (single_win_check([i, j]) === true) {
                    alert("game finished");
                    end_game(color, false);
                }
            }
        }
    }
}


// 判断单个棋子有无胜负。共有8个方向，将竖直向上标记为1，顺时针方向为2， 3， 4， ...， 8。
function single_win_check (pos) {
    let possible_directions = [];
    if (pos[1] - 4 >= 0) {
        possible_directions.push([0, -1]);
    }
    if (pos[1] - 4 >= 0 && pos[0] + 4 <= 10) {
        possible_directions.push([1, -1]);
    }
    if (pos[0] + 4 <= 10) {
        possible_directions.push([1, 0]);
    }
    if (pos[0] + 4 <= 10 && pos[1] + 4 <= 10) {
        possible_directions.push([1, 1]);
    }
    if (pos[1] + 4 <= 10) {
        possible_directions.push([0, 1]);
    }
    if (pos[0] - 4 >= 0 && pos[1] + 4 <= 10) {
        possible_directions.push([-1, 1]);
    }
    if (pos[0] - 4 >= 0) {
        possible_directions.push([-1, 0]);
    }
    if (pos[0] - 4 >= 0 && pos[1] - 4 >= 0) {
        possible_directions.push([-1, -1]);
    }
    for (let i = 0; i < possible_directions.length; i++) {
        if (single_direction_win(pos, possible_directions[i]) === true)
            return true;
    }
    return false;
}


// 单个方向判断胜利
function single_direction_win (pos, direction) {
    let x = direction[0];
    let y = direction[1];
    // 此处不可以连等。
    return chess_state[pos[0]][pos[1]] === chess_state[pos[0] + x][pos[1] + y] &&
        chess_state[pos[0] + x][pos[1] + y] === chess_state[pos[0] + 2 * x][pos[1] + 2 * y] &&
        chess_state[pos[0] + 2 * x][pos[1] + 2 * y] === chess_state[pos[0] + 3 * x][pos[1] + 3 * y] &&
        chess_state[pos[0] + 3 * x][pos[1] + 3 * y] === chess_state[pos[0] + 4 * x][pos[1] + 4 * y];
}


// 判断是否下满
function is_full () {
    for (let i = 0; i < 11; i++) {
        for (let j = 0; j < 11; j++) {
            if (chess_state[i][j] === 0) {
                return false;
            }
        }
    }
    return true;
}


// 按下鼠标时获取鼠标位置并判断能不能放棋子
first_hand_botton.onclick = start_change;
document.onclick = game_start;
game_reset.onclick = () => end_game("white", true);